package com.lg.cms.controller.admin.permmission;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lg.cms.entity.Role;
import com.lg.cms.entity.SuperUser;
import com.lg.cms.service.RoleService;
import com.lg.cms.service.SuperUserService;
import com.lg.cms.utils.Md5Util;
import com.lg.cms.utils.SubjectUtil;
import com.lg.cms.vo.LayerTableVO;
import com.lg.cms.vo.admin.SuperUserVO;
import net.bytebuddy.implementation.bind.annotation.Super;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Description: 超级用户管理
 * @Author: wuyuhang
 * @create: 2020-10-04 16:14
 */

@Controller
@RequestMapping("/admin/user")
public class SuperUserController {

    @Autowired
    SuperUserService superUserService;
    @Autowired
    RoleService roleService;

    /**
     * 超级用户列表
     * @param model
     * @return
     */
    @GetMapping("/list")
    public String list(Model model, HttpServletRequest request){
        model.addAttribute("user", SubjectUtil.getSuperUser());
        model.addAttribute("request", request);
        List<SuperUserVO> superUserList = new ArrayList<>();
        model.addAttribute("roleList", roleService.list());
        superUserService.list().forEach(v -> superUserList.add(superUserService.toSuperUserVO(v)));
        model.addAttribute("superUserList", superUserList);
        return "/admin/authority_management/userCategory";
    }

    /**
     * 分页获取数据
     * 可选(带搜索参数)
     * @param username
     * @param nickname
     * @param roleId
     * @return
     */
    @GetMapping("/page")
    @ResponseBody
    public LayerTableVO<SuperUserVO> page(@RequestParam("page") Integer current, @RequestParam("limit") Integer limit, String username, String nickname, Integer roleId){
        Page<SuperUser> page = new Page<>(current, limit);
        LayerTableVO<SuperUserVO> lvo = new LayerTableVO<>();
        List<SuperUserVO> voList = new ArrayList<>();
        QueryWrapper<SuperUser> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(username)){
            wrapper.like("username", username);
        }
        if(!StringUtils.isEmpty(nickname)){
            wrapper.like("nickname", nickname);
        }
        if(roleId != null){
            wrapper.eq("role_id", roleId);
        }
        superUserService.page(page, wrapper);
        for(SuperUser s: page.getRecords()){
            voList.add(superUserService.toSuperUserVO(s));
        }
        lvo.setCode(0);
        lvo.setCount(page.getTotal());
        lvo.setData(voList);
        return lvo;
    }


    /**
     * 获取超级用户信息
     * @param id
     * @return
     */
    @GetMapping("/get/{id}")
    @ResponseBody
    public R<?> getById(@PathVariable("id") Long id){
        System.out.println("1");
        SuperUser superUser = superUserService.getById(id);
        if(superUser == null){
            System.out.println("为空返回");
            return R.failed("此超级用户不存在");
        }
        //被加密过的数据不能发送给前端, 不提供修改信息中直接修改密码操作
        superUser.setPassword("");
        SuperUserVO vo = superUserService.toSuperUserVO(superUser);
        System.out.println("有值返回");
        return R.ok(vo);
    }
    /**
     * 新增超级用户
     * @param superUser
     * @return
     */
    @PostMapping("/add")
    @ResponseBody
    public R<?> add(SuperUser superUser){
        if(!superUser.checkData()){
            return R.failed("请输入必填数据");
        }
        superUser.setPassword(Md5Util.textToMd5(superUser.getPassword()));
        boolean result = superUserService.save(superUser);
        if(!result){
            return R.failed("创建超级用户失败失败");
        }
        return R.ok(superUser);
    }

    /**
     * 修改超级用户信息, 不包含密码
     * @param superUser
     * @return
     */
    @PutMapping("/update")
    @ResponseBody
    public R<?> update(SuperUser superUser){
        SuperUser oldSuperUser = superUserService.getById(superUser.getId());
        oldSuperUser.setNickname(superUser.getNickname());
        oldSuperUser.setUsername(superUser.getUsername());
        boolean result = superUserService.updateById(oldSuperUser);
        if(!result){
            return R.failed("修改失败");
        }
        return R.ok(superUser);
    }

    /**
     * 重置密码, 如果密码参数为空.则重置为随机密码
     * @param id
     * @param password
     * @return 新密码
     */
    @PutMapping("/resetPassword")
    @ResponseBody
    public R<?> resetPassword(Long id, String password){
        if(id == null){
            return R.failed("超级用户id为空");
        }
        if(StringUtils.isEmpty(password)){
            //使用random工具类随机生成一个长十位的密码
            password = RandomStringUtils.randomAlphanumeric(10);
        }
        String passwordText = password;
        password = Md5Util.textToMd5(password);
        SuperUser superUser = superUserService.getById(id);
        if(superUser == null){
            return R.failed("此超级用户不存在");
        }
        superUser.setPassword(password);
        boolean result = superUserService.updateById(superUser);
        if(!result){
            return R.failed("重置密码失败");
        }
        return R.ok(passwordText);

    }

    /**
     * 获取角色列表
     * @return
     */
    @GetMapping("/role_list")
    @ResponseBody
    public List<Role> getRoleList(){
        return roleService.list();
    }

    /**
     * 设置用户角色
     * @return
     */
    @PutMapping("/set_role")
    @ResponseBody
    public R<?> setRole(Long superUserId, Integer roleId){
        SuperUser superUser = superUserService.getById(superUserId);
        Role role = roleService.getById(roleId);
        if(superUser == null){
            return R.failed("此超级用户不存在");
        }
        if(role == null){
            return R.failed("角色不存在");
        }
        superUser.setRoleId(roleId);
        boolean result = superUserService.updateById(superUser);
        if(!result){
            return R.failed("设置角色失败");
        }
        return R.ok(null);
    }

    @DeleteMapping("/delete")
    @ResponseBody
    public R<?> delete(HttpServletRequest request){
        String [] strArray = request.getParameterValues("superUserIdArray[]");
        Set<Long> idSet = new HashSet<>();
        for(int i = 0; i < strArray.length; i += 1){
            idSet.add(Long.valueOf(strArray[i]));
        }
        boolean result  = superUserService.removeByIds(idSet);
        if(!result){
            return R.failed("删除失败");
        }
        return R.ok(null);
    }
}